package com.zj.study.utils.util;


import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * 对象工具类
 *
 * @author 郑文焕
 * @since 2020.11.1
 **/
public final class SignUtil {

  public  static  String digest(StringBuffer  strToSign,String sMerchantKey) throws Exception {

    //假设已排序字符串为strToSign
    //添加商户密钥
    strToSign.append("&").append(sMerchantKey);
    // 创建加密对象
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    // 传入要加密的字符串,按指定的字符集将字符串转换为字节流
    messageDigest.update(strToSign.toString().getBytes(StandardCharsets.UTF_8));
    byte[] byteBuffer = messageDigest.digest();
    // 將 byte数组转换为16进制string
    return HexString(byteBuffer);
  }

  public  static  String digest(StringBuffer strToSign) throws Exception {

    //假设已排序字符串为strToSign
    // 创建加密对象
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    // 传入要加密的字符串,按指定的字符集将字符串转换为字节流
    messageDigest.update(strToSign.toString().getBytes(StandardCharsets.UTF_8));
    byte[] byteBuffer = messageDigest.digest();
    // 將 byte数组转换为16进制string
    return HexString(byteBuffer);
  }

  public static String HexString(byte[] baSrc)
  {
    if (baSrc == null)
    {
      return "";
    }

    int nByteNum = baSrc.length;
    StringBuilder sbResult = new StringBuilder(nByteNum * 2);

    for (int i = 0; i < nByteNum; i++)
    {
      char chHex;

      byte btHigh = (byte)((baSrc[i] & 0xF0) >> 4);
      if (btHigh < 10)
      {
        chHex = (char)('0' + btHigh);
      }
      else
      {
        chHex = (char)('A' + (btHigh - 10));
      }
      sbResult.append(chHex);

      byte btLow = (byte)(baSrc[i] & 0x0F);
      if (btLow < 10)
      {
        chHex = (char)('0' + btLow);
      }
      else
      {
        chHex = (char)('A' + (btLow - 10));
      }
      sbResult.append(chHex);
    }

    return sbResult.toString();
  }

}
